
from Configurable import *
from Util import *
import os.path
import pwd
import shutil
import subprocess
import sys
import time
import glob


class Daemon (Configurable):
    
    def __init__(self, conf):
        Configurable.__init__(self, conf)
        self.sleep = 5
        self.chosen_vdi = None

    def launch_virtual_machine(self, vdifile):
        vbox_version = shell_exec("VBoxManage --version")
        print "VirtualBox version: %s " % vbox_version 
        vdiname = os.path.splitext(vdifile)[0]
        vbox_start_command = "VBoxSDL --convertSettingsBackup --nofstoggle --nograbonclick --startvm %s " % vdiname
        vbox_process = subprocess.call(vbox_start_command, shell=True)
        #for version 2.2.2: VBoxSDL --nofstoggle --nograbonclick --startvm ${vm_name}
    
    def choose_vdi(self):
        files = os.listdir(self.shared_vdi_dir)
        data = glob.glob("%s/*.vdi" % self.shared_vdi_dir)
        if len(data) == 1:
            return data[0]
        
        print "The following virtual disks can be used by Testcloud:"
        counter = 1
        vdis = {0:0}
        for file in data:
            filepath = os.path.join(self.shared_vdi_dir, file)
            if os.path.isfile(filepath) and os.path.splitext(filepath)[1] == ".vdi":
                print "%d- %s" % (counter, os.path.split(filepath)[1])
                vdis[counter] = filepath
                counter += 1

        chosen = False
        while not chosen:
            vdifile = raw_input("Please choose a virtual disk: ")
            try: vdifile = int(vdifile)
            except ValueError, e: 
                print "Invalid selection." 
                continue
            
            for i in range(1,counter):
                if vdifile == i: 
                    chosen = True
                    return vdis[i]
                
            if not chosen:
                print "Invalid selection."
                
    
    def run(self):
        while True:
            cmd = "ps -eo args | grep -i virtualbox | grep -i testcloud"
            output = shell_exec(cmd)
            lines = output.split("\n")
            found_other_testcloud_running = False
            for line in lines:
                if  line != "" and line.find(cmd) < 0:
                    found_other_testcloud_running = True
                    break  
                
            if not found_other_testcloud_running:
                if self.chosen_vdi == None:
                    self.chosen_vdi = self.choose_vdi()
                user_vdi = os.path.join(self.user_testcloud_home,os.path.split(self.chosen_vdi)[1])
                if os.path.exists(user_vdi):
                   print "Erasing used VDI at %s... " % user_vdi,
                   try:
                       os.remove(user_vdi)
                       print "VDI removed successfully."  
                   except OSError, ose:
                       print "An error occurred while removing the VDI."
                       sys.exit(1)
                else:
                    print "Cannot find path %s" % user_vdi
                    print "Exiting"
                    sys.exit(2)
        
        
                if os.path.exists(self.chosen_vdi):
                    print "Copying original VDI from %s to %s/... " % (self.chosen_vdi, self.user_testcloud_home),
                    try: 
                        destfile_name = os.path.split(self.chosen_vdi)[1]
                        shutil.copyfile(self.chosen_vdi, os.path.join(self.user_testcloud_home, destfile_name))
                        print "File copied successfully."
                    except IOError,e:
                        print str(e) 
                        print "An error occurred."
                        sys.exit(3)            
                else:
                    print "Could not find original VDI %s " % self.chosen_vdi
                    sys.exit(4)
            
            print "Launching the virtual machine named %s...\n" % destfile_name,
            start_time = time.gmtime()
            print "Start time: %s" % time.strftime("%Y-%m-%d %H:%M:%S GMT", start_time)
            self.launch_virtual_machine(destfile_name)
            #      read vm_nb < ${user_dir} / ${testcloud_dir} / vm_nb.log
            #      vm_nb = $((${vm_nb} + 1))
            #      echo ${vm_nb} > ${user_dir} / ${testcloud_dir} / vm_nb.log
            #      testcloud - vm - launcher.sh
            time.sleep(self.sleep)



